package services

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/config"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/common/sdk/tx"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/db_sports"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"longmen/server/pkg/db/redis/cache"
	"time"

	"gorm.io/gorm/clause"
)

type InsertLivesInterface interface {
	Get() models_sports.MatchLives
}

// CrateOrDeleteLives 创建或删除数据
// 如果数据已经是完场的数据，那么数据将会被删除
// 表中只会存在未开赛和进行中的数据
func CrateOrDeleteLives(a []InsertLivesInterface) {
	records := make([]models_sports.MatchLives, 0)
	deleteIds := make([]int, 0)
	var a1, a2 []int
	for _, c := range a {
		tmp := c.Get()
		tmp.StandardMatchStatus = ToStandardMatchStatus(tmp.MatchStatus, tmp.SportID) // 设置 标准状态
		if tmp.IsDone() {
			deleteIds = append(deleteIds, tmp.MatchID)
		} else {
			records = append(records, tmp)
		}
		a1 = append(a1, tmp.MatchID)
		//cache.SetVideoViewerNum(tmp.MatchID, 0)
	}

	var allData []*models_sports.MatchLives
	err := global2.Sport().Find(&allData).Error
	if err != nil {
		global2.Log.Info("获取完场比赛失败：", err)
	}
	for _, v := range allData {
		a2 = append(a2, v.MatchID)
	}

	_, diffValues := utils2.FindCommonValues(a1, a2)
	global2.Log.Debugf("获得差集赛事id:%+v", diffValues)
	if len(diffValues) > 0 {
		deleteIds = append(deleteIds, diffValues...)
	}
	if len(deleteIds) > 0 {
		model := models_sports.MatchLives{}
		err := global2.Sport().Where("match_id in ?", deleteIds).Delete(&model).Error
		if err != nil {
			global2.Log.Info("删除完场比赛失败：", deleteIds, err)
		}
	}

	if len(records) == 0 {
		return
	}
	clauses := clause.OnConflict{
		UpdateAll: true,
	}
	err = global2.Sport().Model(records).Clauses(clauses).CreateInBatches(records, 100).Error
	if err != nil {
		return
	}
}

// 原始比赛状态, 转换为 标准比赛状态.
func ToStandardMatchStatus(rawMatchStatus, sportId int) int {
	standardStatus := 0 // default to unknown ?
	switch sportId {
	case config.FootBall:
		standardStatus = int(models_sports.FootBallMatchStatus(rawMatchStatus).MatchTempScheduleStatus())
	case config.BasketBall:
		standardStatus = int(models_sports.BasketBallMatchStatus(rawMatchStatus).MatchTempScheduleStatus())
	case config.Cricket:
		standardStatus = int(models_sports.CricketMatchStatus(rawMatchStatus).MatchTempScheduleStatus())
	}
	return standardStatus
}

func DeleteByDate(endDate int64) bool {
	lives := models_sports.MatchLives{}
	list := make([]int, 0)
	err := global2.Sport().Model(&lives).
		Where("match_time < ?", endDate).
		Pluck("match_id", &list).Error
	if err != nil {
		global2.Log.Info("查询过期的直播链接失败：", err)
		return false
	}
	if len(list) > 0 {
		err = global2.Sport().Where("match_id in ?", list).Delete(&lives).Error
		if err != nil {
			global2.Log.Error("删除过期的直播链接失败：", err)
			return false
		}
	}

	return true
}

func EndLive(anchorid int) error {
	live, err := db_live.GetLiveParam(map[string]interface{}{"anchorid": anchorid})
	if err != nil {
		return err
	}
	if live.Anchorid <= 0 {
		return nil
	}

	if live.ActivityToggle == 1 {
		// 活动统计
		db_main.ActivityBarrageStat(anchorid, live.Liveid)
	}

	liveHistory, err := db_live.GetLiveHistoryParam(map[string]interface{}{"anchorid": anchorid, "liveid": live.Liveid})
	// 重置主键ID避免可能冲突的可能性
	liveHistory.Id = 0
	if err != nil {
		return err
	}

	//插入直播历史
	cTime := time.Now()
	liveHistory.Anchorid = anchorid
	liveHistory.Liveid = live.Liveid
	liveHistory.Title = live.Title
	liveHistory.Stream = live.Stream
	liveHistory.PullUrl = live.PullUrl
	liveHistory.Categoryid = live.Categoryid
	liveHistory.Orientation = live.Orientation
	liveHistory.StartStamp = live.StartStamp
	liveHistory.EndStamp = cTime.Unix()
	liveHistory.EndTime = cTime
	liveHistory.Status = 5 //1:直播中 2:預約 3:取消預約 4:逾期未播 5:結束
	liveHistory.Matchid = live.Matchid
	liveHistory.SportType = live.SportType
	liveHistory.Heat = live.Hot
	liveHistory.EventTitle = live.EventTitle // 新增：记录赛事标题
	liveHistory.Thumb = live.Thumb           //新增封面
	liveHistory.Platform = int(live.Platform)
	liveHistory.OpenChatNum = live.OpenChatNum
	liveHistory.SendChatNum = live.SendChatNum

	if live.Matchid > 0 {
		match := db_sports.GetMatchById(live.Matchid)
		if match != nil {
			liveHistory.MatchStartTime = match.MatchTime
		}
	}
	// 观众
	var visitor int64
	global2.Live().Model(&models_live.LiveStreamHistory{}).Where("liveid=?", live.Liveid).Count(&visitor)
	liveHistory.ViewerCount = visitor
	//收益
	income, err := db_live.AnchorLiveIDIncome(live.Anchorid, live.Liveid)
	if err == nil {
		liveHistory.GiftProfit = income.Income
		liveHistory.AnchorIncome = income.Income
		liveHistory.OtherGiftPrice = int64(income.EagleDiamond)
	}

	//新增粉丝
	global2.Live().Model(&models_main.AnchorFans{}).Where("live_id=? and anchorid=?", live.Liveid, live.Anchorid).Count(&liveHistory.NewFansCount)

	err = endLive(live, liveHistory)
	if err != nil {
		return err
	}

	cache.DelLiveRoomCache(live.Anchorid)
	//直播间调用
	anchorLive := &cache.AnchorLive{
		Anchorid: live.Anchorid,
		Liveid:   live.Liveid,
		Status:   cache.EndLive,
	}
	err = cache.SetAnchorLive(live.Anchorid, anchorLive)
	if err != nil {
		global2.Log.Debugf("SetAnchorLive Cache error：%v", err)
	}

	//// 已处理
	//models.GetRds().Set(fmt.Sprintf(util.LIVE_END_DONE, liveHistory.Anchorid, liveHistory.Liveid), "1", 24*3600*timehelper.Second)

	stream, err := tx.ForbidLiveStream(live.Stream)
	if err != nil {
		global2.Log.Errorf("腾讯云关流失败;RequestId:%v", stream)
	}

	return nil
}

func endLive(live *models_live.Live, liveHistory *models_live.LiveHistory) error {
	fName := "endLive"
	session := global2.Live().Begin()
	defer func() {
		if r := recover(); r != nil {
			session.Rollback()
		}
	}()

	if err := session.Error; err != nil {
		return fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}

	if err := cache.InsertLiveHistoryByTransactions(session, liveHistory); err != nil {
		session.Rollback()
		return fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}

	if err := db_live.DeleteLiveByTransactions(session, live); err != nil {
		session.Rollback()
		return fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}

	// 更新直播计划表状态
	// 暂时屏蔽，等功能上线开通
	// if err := repository.UpdateLivePlanStatus(session, models_live); err != nil {
	// 	session.Rollback()
	// 	return fmt.Errorf("%s %s", common.Convert(fName), err.Error())
	// }

	// if anchorIncome.Id > 0 {
	// 	if err := repository.UpdateAnchorIncomeByTransactions(session, anchorIncomeCol, anchorIncome); err != nil {
	// 		session.Rollback()
	// 		return fmt.Errorf("%s %s", common.Convert(fName), err.Error())
	// 	}
	// } else {
	// 	if err := repository.InsertAnchorIncomeByTransactions(session, anchorIncome); err != nil {
	// 		session.Rollback()
	// 		return fmt.Errorf("%s %s", common.Convert(fName), err.Error())
	// 	}
	// }

	if err := session.Commit().Error; err != nil {
		session.Rollback()
		return fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}
	//在线时间长处
	inOutData, err := cache.GetLiveRoomAllInOutStatistics(live.Anchorid, live.StartStamp)
	global2.Log.Debugf("%s inOutData length:%+v,err:%v,roomId:%v,live.Liveid:%v", fName, len(inOutData), err, live.Anchorid, live.Liveid)
	if err == nil {
		err = db_live.WriteLiveRoomIoData(live.Liveid, inOutData)
		if err == nil {
			cache.DelLiveRoomUserInOutStatistics(live.Anchorid)
		}
	}
	return nil

}
